// 为需要校验的input框增加 valid 属性

const formatText = (key) => {
    return '您填写的' + key + '格式不正确'
};

const rules = {
    mobile: (v) => {
        if (!v.match(/^1(3|4|5|7|8)\d{9}$/)) {
            return {
                type: 'mobile',
                message: formatText('手机号')
            }
        }
    },
    ltFFFF: (v) => {
        if (v.match(/\u{ffff}-\u{fffff}/u)) {
            return {
                type: "ltFFFF",
                message: "您输入了非法字符"
            }
        }
    },
    noOther: (v) => {
        if (v.match(/[\p{C}]/u)) {
            return {
                type: "noOther",
                message: "您输入了非法字符"
            }
        }
    },
    email: (v) => {
        if (!v.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)) {
            return {
                type: 'email',
                message: formatText('邮箱')
            }
        }
    },
    present: (v) => {
        if (!v.trim())
        return {
            type: "present",
            message: "必填"
        }
    }
};
const check = form => {
    if (!(form && form.elements)) {
        return
    }
    const elements = form.elements;
    let checkResults = [];
    Array.from(elements).filter( item => {
        return item.getAttribute("valid");
    }).map( item => {
        const valids = item.getAttribute("valid").split(",");
        console.log("check",item.value);
        const value = item.value.trim();
        let errorList = [];
        valids.forEach(valid => {
            valid = valid.trim();
            if (rules[valid]){
                let result = rules[valid](value);
                result&& errorList.push(result);
            }
        });

        if (errorList.length){
            checkResults.push({
                dom : item,
                errorArr : errorList,
                name: item.name,
                message:errorList[0].message,
                type: errorList[0].type,
            })
        }
    });
    return checkResults;
};

export {check}